﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dotnet.Code.Extend
{
    partial class Ext
    {
        /// <summary>
        /// Byte[]转化为16进制字符串
        /// </summary>
        /// <param name="data">字节数组</param>
        /// <param name="len">字节数组长度</param>
        /// <returns></returns>
        public static string Byte2HexString(this byte[] data, int len)
        {
            StringBuilder builder = new StringBuilder(data.Length * 2);
            for (int i = 1; i <= len; i++)
            {
                byte b = data[i - 1];
                builder.Append(b.ToString("X2"));
                builder.Append(" ");
            }
            return builder.ToString();
        }
        public static string Byte2HexString(this byte[] data)
        {
            return Byte2HexString(data, data.Length);
        }
        /// <summary>
        /// 打印字节数组
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <param name="idx">起始位置</param>
        /// <param name="count">总字符长度</param>
        /// <param name="spliter">分隔符</param>
        /// <returns></returns>
        public static string Byte2String(this byte[] bytes, int idx, int count, string spliter = "")
        {
            StringBuilder sb = new StringBuilder();

            if (bytes == null || bytes.Length == 0 || idx < 0 || count < 0)
                return "";

            for (int i = idx; i < bytes.Length && i < count; i++)
            {
                sb.Append(bytes[i].ToString("x2"));

                if (i != bytes.Length - 1 && spliter != "")
                {
                    sb.Append(spliter);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 取一个字节的高四位
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static int GetByteHeight4(this byte data)
        {//获取高四位
            int height;
            height = ((data & 0xf0) >> 4);
            return height;
        }
        /// <summary>
        /// 取一个字节的低四位
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static int GetByteLow4(this byte data)
        {//获取低四位
            int low;
            low = (data & 0x0f);
            return low;
        }
        /// <summary>
        /// 取两字节各自低四位拼接为一个字节
        /// </summary>
        /// <param name="b1"></param>
        /// <param name="b2"></param>
        /// <returns></returns>
        public static int Concat2BytesLow4(this byte[] bytes)
        {
            if (bytes.Length != 2)
                return -1;
            byte b1 = bytes[0];
            byte b2 = bytes[1];
            int sum = ((b1 & 0x0F) << 4) + (b2 & 0x0F);
            return sum;
        }
    }
}
